//
//  URLParser.m
//  mobile
//
//  Created by Demi on 7/5/16.
//  Copyright © 2016 azazie. All rights reserved.
//

#import "URLParser.h"

@interface URLParser ()

@property (nonatomic, strong) NSArray *variables;

@end

@implementation URLParser

+ (NSDictionary *)parseURLAbsolutelly:(NSString *)url {
    URLParser *parser = [[URLParser alloc] initWithURLString:url];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:parser.variables.count];
    [parser.variables enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *temp = [obj componentsSeparatedByString:@"="];
        params[temp[0]] = temp[1];
    }];
    return params;
}

- (id) initWithURLString:(NSString *)url{
    self = [super init];
    if (self != nil) {
        NSString *string = url;
        NSScanner *scanner = [NSScanner scannerWithString:string];
        [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"&?"]];
        NSString *tempString;
        NSMutableArray *vars = [NSMutableArray new];
        //ignore the beginning of the string and skip to the vars
        [scanner scanUpToString:@"?" intoString:nil];
        while ([scanner scanUpToString:@"&" intoString:&tempString]) {
            [vars addObject:tempString];
        }
        self.variables = vars;
    }
    return self;
}

- (NSString *)valueForVariable:(NSString *)varName {
    for (NSString *var in _variables) {
        if ([var length] > [varName length]+1 && [[var substringWithRange:NSMakeRange(0, [varName length]+1)] isEqualToString:[varName stringByAppendingString:@"="]]) {
            NSString *varValue = [var substringFromIndex:[varName length]+1];
            return varValue;
        }
    }
    return nil;
}


@end
